package search

import (
	"context"
	"encoding/json"
	"time"

	"gitee.com/liuyun-luo/MagicStreamMovies/Server/config"
	"gitee.com/liuyun-luo/MagicStreamMovies/Server/utils"
	"github.com/gin-gonic/gin"
)

// 向搜索引擎发送搜索内容，并获取其返回的结果
func SearchMovie(ctx *gin.Context, keyword string) ([]uint, error) {
	//创建/获取一个消息队列
	mq := utils.NewQueue(config.MovieSearchListKeyName)

	msg := utils.NewMassage(keyword, time.Now())

	if err := mq.Push(*msg); err != nil {
		return nil, err
	}

	//读取操作设置30秒超时
	cont, canel := context.WithTimeout(ctx, time.Second*30)
	defer canel()

	movie_ids, err := mq.Pop(cont)
	if err != nil {
		return nil, err
	}
	var resultFormat struct {
		MovieIDs []uint `json:"movie_ids"`
	}

	//获取搜索到的电影的id列表
	if err := json.Unmarshal([]byte(movie_ids.Content), &resultFormat); err != nil {
		return nil, err
	}

	return resultFormat.MovieIDs, nil
}

// 向搜索引擎发送AI推荐的电影名字，并获取其返回的结果
func SearchAIRecommendMovie(ctx *gin.Context, keyword AIRecommendSearchRequest) (AIRecommendSearchResponse, error) {
	//创建/获取一个消息队列
	mq := utils.NewQueue(config.MovieSearchListKeyName)

	keyword_json, err := json.Marshal(keyword)
	if err != nil {
		return AIRecommendSearchResponse{}, err
	}

	msg := utils.NewMassage(string(keyword_json), time.Now())

	if err := mq.Push(*msg); err != nil {
		return AIRecommendSearchResponse{}, err
	}

	//读取操作设置30秒超时
	cont, canel := context.WithTimeout(ctx, time.Second*30)
	defer canel()

	movie_ids, err := mq.Pop(cont)
	if err != nil {
		return AIRecommendSearchResponse{}, err
	}
	var result AIRecommendSearchResponse

	//获取搜索到的电影的id列表
	if err := json.Unmarshal([]byte(movie_ids.Content), &result); err != nil {
		return AIRecommendSearchResponse{}, err
	}

	return result, nil
}

